package com.net;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


/**
 * 
 * @Description: 返回参数数组形式反射成对象数据工具类
 * @author whq
 * @date 2016年5月13日 下午5:49:42
 *
 */
public class ResponseDataFormatObj {
	
	/**
	 * <pre>解析数据对象，可包含List</pre>
	 * @param data
	 * @param t
	 * @return
	 * @return T
	 */
	public static <T> T parserObj(String data, Class<T> t)  {
	        if(data!=null){
	        	 String[]objArr=data.split(Character.SEPARATOR,-1);
	            try {
	            	T bean= t.newInstance();
	                Method method= t.getMethod("getKeySort");
	                Object obj=method.invoke(bean);
	                if(obj instanceof  String[]){
	                    String[] keySort= (String[]) obj;
	                    //以最小数据为准
	                    int len=Math.min(keySort.length, objArr.length);
	                    for (int i = 0; i < len; i++) {
	                       // L.d("keySort "+i+" = [" + keySort[i] + "]");
	                        Field field= t.getDeclaredField(keySort[i]);
	                        field.setAccessible(true);
	                        if(field.getType().isAssignableFrom(ArrayList.class)||field.getType().isAssignableFrom(List.class)){
	                            ArrayList<T>  ar= (ArrayList<T> )parserArray(bean,objArr[i],field);
	                            // L.d("ar = [" + ar.toString() + "]");
	                            field.set(bean,ar);
	                        }else{
	                            field.set(bean,objArr[i]);
	                        }
	                    }
	                }
	                return  bean;
	            } catch (NoSuchMethodException e) {
	            	 System.out.println("error = [" + e.getMessage() + "] 没有getKeySort 方法");
	            } catch (IllegalAccessException e) {
	                System.out.println("error = [" + e.getMessage() + "]");
	            } catch (InstantiationException e) {
	            	 System.out.println("error = [" + e.getMessage() + "]");
	            } catch (InvocationTargetException e) {
	            	 System.out.println("error = [" + e.getMessage() + "]");
	            } catch (NoSuchFieldException e) {
	            	 System.out.println("error = [" + e.getMessage() + "] 没有相应的字段属性");
	            }
	        }
	        return null;
	    }

	/**
	 * <pre>只解析为数组的String</pre>
	 * @param data
	 * @param clazz ArrayList 中泛型类
	 * @return ArrayList<T>
	 */
	public static <T> ArrayList<T> parserArray(String data, Class<T> clazz) {
		if (data != null && data.contains(Character.SEPARATOR_DATA)) {
			String[] list = data.split(Character.SEPARATOR_DATA_PRE, -1);
			ArrayList<T> arrList = new ArrayList<T>(list.length);
			try {
				String[] keySort = null;
				for (int i = 0; i < list.length; i++) {
					T bean = clazz.newInstance();
					if (keySort == null) {// 只取一次
						Method method = clazz.getMethod("getKeySort");
						Object obj = method.invoke(bean);
						keySort = (String[]) obj;
					}
					String str = list[i];
					if (!str.contains(Character.SEPARATOR_DATA)) {
						continue;
					}
					String[] objArr = str.split(Character.SEPARATOR_DATA, -1);
					int len = Math.min(keySort.length, objArr.length);
					// L.d(objArr.toString());
					for (int j = 0; j < len; j++) {
						// L.d(keySort[j]+" ;");
						Field field1 = clazz.getField(keySort[j]);
						field1.setAccessible(true);
						field1.set(bean, objArr[j]);
					}
					arrList.add((T) bean);
				}
			} catch (InstantiationException e) {
				System.out.println("error = [" + e.getMessage() + "]");
			} catch (IllegalAccessException e) {
				System.out.println("error = [" + e.getMessage() + "]");
			} catch (NoSuchMethodException e) {
				System.out.println("error = [" + e.getMessage() + "] 没有getKeySort 方法");
			} catch (IllegalArgumentException e) {
				System.out.println("error = [" + e.getMessage() + "]");
			} catch (InvocationTargetException e) {
				System.out.println("error = [" + e.getMessage() + "]");
			} catch (NoSuchFieldException e) {
				System.out.println("error = [" + e.getMessage() + "] 没有相应的字段属性");
			}
			return arrList;
		}
		return null;
	}

	  
	    /**
	     * <pre>解析数组数据</pre>
	     * @param ob
	     * @param data
	     * @param field
	     * @return ArrayList<?>
	     */
	    @SuppressWarnings("unchecked")
	public static <T> ArrayList<T> parserArray(T ob, String data, Field field) {
		Type genType = field.getGenericType();// t.getGenericSuperclass();
		if (!(genType instanceof ParameterizedType)) {// i
			// return Object.class;
			return null;
		}
		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
		if (params != null) {
			String[] list = data.split(Character.SEPARATOR_DATA_PRE, -1);
			ArrayList<T> arrList = new ArrayList<T>(list.length);
			// L.d("param0 = [" + params[0] + "]");
			Type type = params[0];
			try {
				// Class<?> clazz= Class.forName(type.);
				Class<?> clazz = (Class<?>) type;
				// if(!clazz.isAssignableFrom(String.class)){
				String[] keySort = null;
				for (int i = 0; i < list.length; i++) {//
					Object bean = null;
					if (clazz.getName().contains(Character.SEPARATOR_DATA_$)) {// 内部类
						bean = clazz.getDeclaredConstructors()[0].newInstance(ob);
					} else {
						bean = clazz.newInstance();
					}
					if (keySort == null) {
						Method method = clazz.getMethod("getKeySort");
						Object obj = method.invoke(bean);
						keySort = (String[]) obj;
					}
					String str = list[i];
					// L.d("sub="+str);
					String[] objArr = str.split(Character.SEPARATOR_DATA, -1);
					int len = Math.min(keySort.length, objArr.length);
					// L.d(objArr.toString());
					for (int j = 0; j < len; j++) {
						// L.d(keySort[j]+" ;");
						Field field1 = clazz.getField(keySort[j]);
						field1.setAccessible(true);
						field1.set(bean, objArr[j]);
					}
					arrList.add((T) bean);
				}
				return arrList;
				// }
			} catch (NoSuchMethodException e) {
				System.out.println("error = [" + e.getMessage() + "]");
			} catch (IllegalAccessException e) {
				System.out.println("error = [" + e.getMessage() + "]");
			} catch (InvocationTargetException e) {
				System.out.println("error = [" + e.getMessage() + "]");
			} catch (InstantiationException e) {
				System.out.println("error = [" + e.getMessage() + "]");
			} catch (NoSuchFieldException e) {
				System.out.println("error = [" + e.getMessage() + "] 没有相应的字段属性");
			}
		}

		return null;
	}
	

    /**使用反射解析数据*/
	/*
	 public static BaseResponse parseResponseDataForReflect(String[] response, Class t) {
		BaseResponse bResponse = new BaseResponse();
		try {
			Object OB = t.newInstance();// 生成对象
			Field[] fields = t.getDeclaredFields();// 获取字段数组
			Field field_keySort = t.getField("keySort");// 获取索引
			String[] keysort = (String[]) field_keySort.get(OB);// 索引元素数组
			int len = response.length;
			// Field[] fields = resp.getClass().getFields();
			if (fields != null) {
				for (int i = 0; i < keysort.length; i++) { // 循环取解析bean参数
					String keyName = keysort[i];
					if (i >= len) {// 跳出循环
						break;
					}
					Field field = t.getDeclaredField(keyName);
					field.setAccessible(true);// 设置可访问

					Log.e("whq_name:", field.getName() + "  whq_value:" + response[i]);
					if (field.getType() != null && field.getType().isAssignableFrom(String[].class)) {// 判断参数是否是String数组

					} else if (field.getType() != null && field.getType().isAssignableFrom(List.class)) {// 判断参数类型是否为list类型

						Type fType = (Type) field.getGenericType();
						ParameterizedType fG = (ParameterizedType) fType;
						Class genericClazz = (Class) fG.getActualTypeArguments()[0];
                         ArrayList<?> list = getInnerClassObj(OB, genericClazz, response[i].split("~", -1));
						field.set(OB, list);

					} else { // 普通字段赋值
						field.set(OB, response[i].toString());// field赋值
					}

				}
			}
			bResponse.t = OB;
		  
			return bResponse;
		} catch (Exception e) {
			return null;
		}

	}*/

	/**
	 * 
	 * @Title: getInnerClassObj
	 * @Description: TODO 获取泛型对象数据
	 * @param
	 * @return 设定文件 @return Object 返回类型 @throws
	 */
	/*
	public static ArrayList<?> getInnerClassObj(Object ob, Class clazzs, String[] strs) {

		ArrayList list = new ArrayList<Object>();
		try {

			Class innerClass = clazzs;
			Object innerObj = null;
			if (innerClass.getName().contains("$")) {// 内部类
				innerObj = innerClass.getDeclaredConstructors()[0].newInstance(ob);
			} else {
				innerObj = innerClass.newInstance();
			}
			Field[] fields = innerClass.getDeclaredFields();
			Field field_keySort = innerClass.getField("innerKeySort");// 获取索引
			String[] keysort = (String[]) field_keySort.get(innerObj);// 索引元素数组

			// 循环内部中的索引参数

			for (String str : strs) {
				Object inneObjs = null;
				if (innerClass.getName().contains("$")) {// 内部类
					inneObjs = innerClass.getDeclaredConstructors()[0].newInstance(ob);
				} else {
					inneObjs = innerClass.newInstance();
				}

				String[] innerParams = str.split("\\|", -1);
				for (int k = 0; k < innerParams.length; k++) {
					// 判断sort长度与 切割出数组长度，避免角标越界
					String keyName = keysort[k];
					Field field = innerClass.getDeclaredField(keyName);
					field.setAccessible(true);
					field.set(inneObjs, innerParams[k].toString());

				}

				list.add(inneObjs);
			}

		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return list;
	}*/
}
